<?php
class Node extends AppModel {

	var $name = 'Node';
	var $useTable = "nodes_nodes";
	var $do_afterSave = true;
	var $actsAs = array(
		'Extend.Sluggable' => array('separator' => '_', 'overwrite' => true),
		'Extend.SoftDeletable' => array(),
		'Tree'
	);
	var $validate = array(
		'title' => array('notempty')
	);
	
	function fetch($id = null, $type = 'node') {
		$filename = "views".DS."nodes_fetch_" . $id . '_' . $type;
		
		$data = cache($filename);
		if($data != null) {
			$return = unserialize($data); 
		} else {
			if($id == null) {
				//$nodes = $this->findByParentId(null);
				$params = array(
					'conditions' => array('Node.published' => 1),
					'fields' => array('Node.id'),
					'order' => array('Node.lft' => 'asc')
				);

				$node = $this->find('first', $params);
				$id = $node['Node']['id'];
			}
			switch ($type) {
				case 'node':
					$return = $this->read(null, $id);
				break;
				case 'children':
					$children = $this->children($id, true);
					$return = $children;
				break;
				case 'menu':
					//$nodes = $this->findAllByParentId(null);
					$params = array(
						'conditions' => array('Node.published' => 1, 'Node.parent_id' => null),
						'fields' => array('Node.id', 'Node.title', 'Node.slug', 'Node.shortcut', 'Node.path'),
						'order' => array('Node.lft' => 'asc')
					);

					$nodes = $this->find('all', $params);
					//debug($nodes);
					$return = $nodes;
				break;
			}
			//debug($settings);
			cache($filename, serialize($return));
		}
		
		return $return;
	}
	
	function beforeDelete($cascade) {
		$return = parent::beforeSave($created);
		$this->do_afterSave = false;
		return $return;
	}
	
	function sync() {
		$nodes = $this->find('all');
		foreach($nodes as $node) {
			$this->save($node);
		}
	}
	
	function afterSave($created) {
		$return = parent::beforeSave($created);
		if(isset($this->id) and $this->do_afterSave) {
			//debug($this);
			$node = $this->read(null, $this->id);
			$path_array = $this->getpath($this->id, $this->alias . '.slug');
			$path_array2 = Set::classicExtract($path_array, '{n}.Node.slug');
			
			// Use if you only want one root node
			//array_shift($path_array2);
			
			$depth = count($path_array2);
			$path = join('/', $path_array2);
			
			//$path = "/" . join('/', $path_array2);
			$path = join('/', $path_array2);

			if($node[$this->alias]['path'] != $path) {
				$this->saveField('path', $path);
			}
			if($node[$this->alias]['depth'] != $depth) {
				$this->saveField('depth', $depth);
			}
		}

		return $return;
	}
}
?>